package Thread;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author liyang
 * @version 1.0
 * @package Thread
 * @file ThreadPoolDemo.java
 * @description
 * @time 2024/7/12 下午2:56
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
//        创建线程池并设置相关参数
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
//        假装这是三个不同的任务，由两个线程并发执行，最终三个任务都执行完毕
//        根据执行的顺序不同，有可能1线程执行了两个任务~~~
        for (int i = 0; i < 3; i++) {
            Runnable r = new Runnable() {
                public void run() {
                    Thread t = Thread.currentThread();
                    System.out.println(t.getName()+":开始执行任务");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(t.getName()+":任务执行完毕");
                }
            };
            /*跑完一个任务后，为了复用，将其放入到线程池中，以前是：
            Runnable r2 = new MyRunnable2();
            Thread t1 = new Thread(r1);*/

            threadPool.execute(r);
            System.out.println("此任务已经放入线程池");


        }

        threadPool.shutdown();
//        threadPool.shutdownNow();
        System.out.println("线程池停止了");
    }
}
